package com.moji.service.impl;


import com.moji.config.WeChatConfig;
import com.moji.common.utils.CommonUtil;
import com.moji.common.utils.HttpUtils;
import com.moji.common.utils.WXPayUtil;
import com.moji.entity.MjOrder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.net.ssl.HttpsURLConnection;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

@Service

public class WeChatService {
	@Autowired
	private WeChatConfig weChatConfig;

	/**
	 * 微信统一下单方法 生成用户扫码支付的二维码的URL
	 * https://pay.weixin.qq.com/wiki/doc/api/native.php?chapter=9_1
	 * 除付款码支付场景以外，商户系统先调用该接口在微信支付服务后台生成预支付交易单，返回正确的预支付交易会话标识后再按Native、JSAPI、APP等不同场景生成交易串调起支付。
	 * @return
	 */
	public String unifiedOrder(MjOrder order) throws Exception {

		//int i = 1/0;   //模拟异常
		//生成签名
		SortedMap<String,String> params = new TreeMap<>();
		params.put("appid",weChatConfig.getAppId());
		params.put("mch_id", weChatConfig.getMchId());
		params.put("nonce_str", CommonUtil.generateUUID());
		params.put("body", "墨迹产品");
		params.put("out_trade_no",order.getOrderCode());
		params.put("total_fee",String.valueOf(order.getOrderAmount().multiply(new BigDecimal(100)).intValue()));
//		params.put("total_fee","1");
//		params.put("spbill_create_ip",order.getIp());
		params.put("notify_url",weChatConfig.getPayCallbackUrl());
		params.put("trade_type","NATIVE");

		//sign签名
		String sign = WXPayUtil.createSign(params, weChatConfig.getKey());
		params.put("sign",sign);

		//map转xml
		String payXml = WXPayUtil.mapToXml(params);

//		log.info("------------#####################-------------payXml={}",payXml);

		//统一下单
		HttpsURLConnection conn = (HttpsURLConnection) new URL("https://api.mch.weixin.qq.com/pay/unifiedorder").openConnection();
		conn.setRequestMethod("POST");
		conn.setRequestProperty("Content-Type", "application/xml");
		conn.setDoOutput(true);

		OutputStream out = conn.getOutputStream();
		out.write(payXml.getBytes(StandardCharsets.UTF_8));
		out.flush();
		out.close();

		// 获取返回结果
		BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8));
		StringBuilder response = new StringBuilder();
		String line;
		while ((line = in.readLine()) != null) {
			response.append(line);
		}
		in.close();
		conn.disconnect();

// 解析返回的XML结果




//		String orderStr = HttpUtils.doPost(WeChatConfig.getUnifiedOrderUrl(),payXml,4000);
//		if(null == orderStr) {
//			return null;
//		}
//		log.info("------------#####################-------------orderStr={}",orderStr);

		Map<String, String> unifiedOrderMap =  WXPayUtil.xmlToMap(response.toString());
		System.out.println(unifiedOrderMap.toString());
		if(unifiedOrderMap != null) {
//			log.info("------------#####################-------------code_url={}",unifiedOrderMap.get("code_url"));
			return unifiedOrderMap.get("code_url");
		}

		return null;
	}

    public static void main(String[] args) {

	}
}
